package com.shangxian.giveithome.controller;

import com.shangxian.giveithome.annoaction.CheckLoginStatus;
import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.entity.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.PetMapper;
import com.shangxian.giveithome.result.Result;
import com.shangxian.giveithome.service.PetService;
import com.shangxian.giveithome.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.HashMap;

import static com.shangxian.giveithome.code.PetCode.*;
import static com.shangxian.giveithome.properties.UserProperties.ROLE_MECHANISM;

@Api(tags = "宠物模块")
@RestController
@RequestMapping("/pets")
@Slf4j
public class PetController {

    @Autowired
    private PetService petService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private HttpServletRequest request;

    @Resource
    private PetMapper petMapper;

    @ApiOperation(value = "查询全部")
    @GetMapping(value = "/querySearchAllList", name = "查询全部")
    public Result getSearchAll(SearchScreen searchScreen, @PageableDefault(page = 0, size = 10) Pageable pageable) {
        return Result.success(petService.querySearchAll(searchScreen, pageable));
    }

    @ApiOperation(value = "寻宠列表")
    @GetMapping(value = "/querySearchPetList", name = "寻宠列表")
    public Result getSearch_Pet(SearchScreen searchScreen, @PageableDefault(page = 0, size = 10) Pageable pageable) {

        return Result.success(petService.querySearchPet(searchScreen, pageable));
    }

    @ApiOperation(value = "寻主列表")
    @GetMapping(value = "/querySearchPeopleList", name = "寻主列表")
    public Result getSearch_People(SearchScreen searchScreen, @PageableDefault(page = 0, size = 10) Pageable pageable) {
        return Result.success(petService.querySearchPeople(searchScreen, pageable));
    }

    @ApiOperation(value = "查看寻宠详情")
    @GetMapping("/querySearchPetDetails/{id}")
    public Result getSearch_PetDetails(@PathVariable Long id) {
        return Result.success(petService.querySearchPetDetails(id));
    }

    @ApiOperation(value = "查看寻主详情")
    @GetMapping("/querySearchPeopleDetails/{id}")
    public Result getSearch_PeopleDetails(@PathVariable Long id) {
        return Result.success(petService.querySearchPeopleDetails(id));
    }

    @ApiOperation(value = "查询机构详情正在进行的送养")
    @GetMapping(value = "/queryPlaceMe/{id}/{n}", name = "查询机构详情正在进行的送养")
    public Result queryPlaceMe(@PathVariable Long id, @PathVariable Integer n) {
        return Result.success(petService.queryPlaceMe(id, n));
    }


    @ApiOperation(value = "查看送养列表")
    @GetMapping(value = "/queryPlaces", name = "查看送养列表")
    public Result queryPlace(PlaceScreen placeScreen, @PageableDefault(page = 0, size = 10) Pageable pageable) {
        return Result.success(petService.queryPlace(placeScreen, pageable));
    }

    @ApiOperation(value = "查看领养详情")
    @GetMapping("/queryPlaceDetails/{id}")
    public Result queryPlaceDetails(@PathVariable Long id) {
        return Result.success(petService.queryPlaceDetails(id));
    }

    @ApiOperation(value = "发布寻宠")
    @PostMapping(value = "/createSearchPet", name = "发布寻宠")
    public Result createSearchPet(@RequestBody SearchPetCreate searchPetCreate) {
        UserDetails header = redisUtils.getHeader(request);
        /*if (searchPetCreate.getMeId()!=null) {
            searchPetCreate.setUsId(null);
            searchPetCreate.setMeId(header.getMechanism().getId());
            searchPetCreate.setWechat(header.getMechanism().getWechat());
            searchPetCreate.setPhone(header.getMechanism().getPhone());
        } else {
            searchPetCreate.setMeId(null);
            searchPetCreate.setUsId(header.getId());
            searchPetCreate.setWechat(header.getWechat());
            searchPetCreate.setPhone(header.getPhone());
        }*/
        searchPetCreate.setUsId(header.getId());
        // 是否为机构
        if (header.getRole().equals(ROLE_MECHANISM)) {
            searchPetCreate.setMeId(header.getMechanism().getId());
//            searchPetCreate.setWechat(header.getMechanism().getWechat());
//            searchPetCreate.setPhone(header.getMechanism().getPhone());
        } else {
            searchPetCreate.setMeId(0L);
//            searchPetCreate.setWechat(header.getWechat());
//            searchPetCreate.setPhone(header.getPhone());
        }
        int petId = petService.createSearchPet(searchPetCreate);
        HashMap<String, Integer> result = new HashMap<>();
        result.put("petId",petId);
        return Result.success(result);
    }

    @ApiOperation(value = "修改寻宠")
    @PutMapping(value = "/updateSearchPet", name = "修改寻宠")
    public Result updateSearchPet(@RequestBody SearchPetUpdate searchPetUpdate) {
        UserDetails header = redisUtils.getHeader(request);
        System.out.println(searchPetUpdate);
        if (searchPetUpdate != null) {
            int i = petMapper.findPetByIdAndSub(searchPetUpdate.getId(), 1);
            if (i < 1) {
                Result.error(CommonCode.DATA_ERRORS);
            }
            searchPetUpdate.setUsId(header.getId());
            petService.updateSearchPet(searchPetUpdate);
            return Result.success();
        }else {
            return  Result.error(CommonCode.DATA_ERROR);
        }
//        int i = petMapper.findPetByIdAndSub(searchPetUpdate.getId(), 1);
//        if (i<1){
//            Result.error(CommonCode.DATA_ERRORS);
//        }
//        /*if (searchPetUpdate.getMeId()!=null) {
//            searchPetUpdate.setWechat(header.getMechanism().getWechat());
//            searchPetUpdate.setPhone(header.getMechanism().getPhone());
//        } else {
//            searchPetUpdate.setWechat(header.getWechat());
//            searchPetUpdate.setPhone(header.getPhone());
//        }*/
//        searchPetUpdate.setUsId(header.getId());
////        if (header.getRole().equals(ROLE_MECHANISM)) {
////            searchPetUpdate.setWechat(header.getMechanism().getWechat());
////            searchPetUpdate.setPhone(header.getMechanism().getPhone());
////        } else {
////            searchPetUpdate.setWechat(header.getWechat());
////            searchPetUpdate.setPhone(header.getPhone());
////        }
//        petService.updateSearchPet(searchPetUpdate);
//        return Result.success();
    }

    @ApiOperation(value = "删除寻宠")
    @DeleteMapping("/deleteSearchPet/{id}")
    @CheckLoginStatus
    public Result deleteSearchPet(@PathVariable Long id) {
        petService.deleteSearchPet(id);
        return Result.success();
    }

    @ApiOperation(value = "找到宠物了")
    @PutMapping("/searchPetSuccess/{id}")
    @CheckLoginStatus
    public Result SearchPetSuccess(@PathVariable Long id){
        petService.updateSearchPetStatus(id);
        return Result.success();
    }

    @ApiOperation(value = "发布寻主")
    @PostMapping(value = "/createSearchPeople", name = "发布寻主")
    public Result createSearchPeople(@RequestBody SearchPeopleCreate searchPeopleCreate) {
        UserDetails header = redisUtils.getHeader(request);
        /*if (searchPeopleCreate.getMeId()!=null) {
            searchPeopleCreate.setMeId(header.getMechanism().getId());
            searchPeopleCreate.setWechat(header.getMechanism().getWechat());
            searchPeopleCreate.setPhone(header.getMechanism().getPhone());
        } else {
            searchPeopleCreate.setUsId(header.getId());
            searchPeopleCreate.setWechat(header.getWechat());
            searchPeopleCreate.setPhone(header.getPhone());
        }*/
        searchPeopleCreate.setUsId(header.getId());
        // 是否为机构
        if (header.getRole().equals(ROLE_MECHANISM)) {
            searchPeopleCreate.setMeId(header.getMechanism().getId());
//            searchPeopleCreate.setWechat(header.getMechanism().getWechat());
//            searchPeopleCreate.setPhone(header.getMechanism().getPhone());
        } else {
            searchPeopleCreate.setMeId(0L);
//            searchPeopleCreate.setWechat(header.getWechat());
//            searchPeopleCreate.setPhone(header.getPhone());
        }
        int petId = petService.createSearchPeople(searchPeopleCreate);
        HashMap<String, Integer> result = new HashMap<>();
        result.put("petId",petId);
        return Result.success(result);
    }

    @ApiOperation(value = "修改寻主")
    @PutMapping(value = "/updateSearchPeople", name = "修改寻主")
    public Result updateSearchPeople(@RequestBody SearchPeopleUpdate searchPeopleUpdate) {
        UserDetails header = redisUtils.getHeader(request);
        System.out.println(searchPeopleUpdate);
        if (searchPeopleUpdate != null) {
            int i = petMapper.findPetByIdAndSub(searchPeopleUpdate.getId(), 2);
            if (i < 1) {
                Result.error(CommonCode.DATA_ERRORS);
            }
            searchPeopleUpdate.setUsId(header.getId());
            petService.updateSearchPeople(searchPeopleUpdate);
            return Result.success();
        }else {
            return  Result.error(CommonCode.DATA_ERROR);
        }

        /*if (searchPeopleUpdate.getMeId()!=null) {
            searchPeopleUpdate.setWechat(header.getMechanism().getWechat());
            searchPeopleUpdate.setPhone(header.getMechanism().getPhone());
        } else {
            searchPeopleUpdate.setWechat(header.getWechat());
            searchPeopleUpdate.setPhone(header.getPhone());
        }*/


        // 是否为机构
//        if (header.getRole().equals(ROLE_MECHANISM)) {
//            searchPeopleUpdate.setWechat(header.getMechanism().getWechat());
//            searchPeopleUpdate.setPhone(header.getMechanism().getPhone());
//        } else {
//            searchPeopleUpdate.setWechat(header.getWechat());
//            searchPeopleUpdate.setPhone(header.getPhone());
//        }

    }

    @ApiOperation(value = "删除寻主")
    @DeleteMapping("/deleteSearchPeople/{id}")
    @CheckLoginStatus(state = false )
    public Result deleteSearchPeople(@PathVariable Long id) {
        petService.deleteSearchPeople(id);
        return Result.success();
    }

    @ApiOperation(value = "找到主人了")
    @PutMapping("/searchPeopleSuccess/{id}")
    @CheckLoginStatus
    public Result SearchPeopleSuccess(@PathVariable Long id){
        petService.updateSearchPeopleStatus(id);
        return Result.success();
    }

    @ApiOperation(value = "发布领养")
    @PostMapping(value = "/createPlace", name = "发布领养")
    public Result createPlace(@Valid @RequestBody PlaceCreate petCreate) {
        UserDetails header = redisUtils.getHeader(request);
        petCreate.setUsId(header.getId());
        // 是否为机构
        if (header.getRole().equals(ROLE_MECHANISM)) {
            petCreate.setMeId(header.getMechanism().getId());
//            petCreate.setWechat(header.getMechanism().getWechat());
//            petCreate.setPhone(header.getMechanism().getPhone());
        } else {
            petCreate.setMeId(0L);
//            petCreate.setWechat(header.getWechat());
//            petCreate.setPhone(header.getPhone());
        }
        int petId = petService.createPlace(petCreate);
        HashMap<String, Integer> result = new HashMap<>();
        result.put("petId",petId);
        return Result.success(result);
    }

    @ApiOperation(value = "修改领养")
    @PutMapping(value = "/updatePlace", name = "修改领养")
    public Result updatePlace(@Valid @RequestBody PlaceUpdate placeUpdate) {
        UserDetails header = redisUtils.getHeader(request);
        // 是否为机构
//        if (header.getRole().equals(ROLE_MECHANISM)) {
//            placeUpdate.setWechat(header.getMechanism().getWechat());
//            placeUpdate.setPhone(header.getMechanism().getPhone());
//        } else {
//            placeUpdate.setWechat(header.getWechat());
//            placeUpdate.setPhone(header.getPhone());
//        }
        placeUpdate.setUsId(header.getId());
        petService.updatePlace(placeUpdate);
        return Result.success();
    }

    @ApiOperation(value = "删除送养")
    @DeleteMapping(value = "/delPlace/{petId}", name = "删除送养")
    public Result delPlace(@PathVariable Long petId) {
        UserDetails header = redisUtils.getHeader(request);
        petService.delPlace(petId, header.getId());
        return Result.success();
    }

    @ApiOperation(value = "领养协议创建-送养方修改图片信息")
    @PutMapping(value = "/updateAdoptionImg", name = "领养协议创建-送养方修改图片信息")
    public Result updateAdoptionImg(@Valid @RequestBody AdoptionImg adoptionImg) {
        UserDetails header = redisUtils.getHeader(request);
        petService.updateAdoptionImg(adoptionImg, header.getId());
        return Result.success();
    }

    @ApiOperation(value = "领养协议创建-送养方")
    @PostMapping(value = "/createAdoption", name = "领养协议创建-送养方")
    public Result adoptionCreate(@Valid @RequestBody AdoptionCreate adoptionCreate) {
        UserDetails header = redisUtils.getHeader(request);
        Adoption adoption = new Adoption();
        adoption.setPetId(adoptionCreate.getPetId());
        adoption.setUsId(header.getId());
        adoption.setAdId(0);
        // 是否为机构
        if (header.getRole().equals(ROLE_MECHANISM)) {
            adoption.setMeId(header.getMechanism().getId());
        } else {
            adoption.setMeId(0L);
        }
        adoptionCreate.setAdoption(adoption);
        petService.createAdoption(adoptionCreate);
        return Result.success();
    }

    @ApiOperation(value = "领养协议完成-领养方")
    @PostMapping(value = "/adoptionComplete", name = "领养协议完成-领养方")
    public Result adoptionComplete(@Valid @RequestBody AdoptionComplete adoptionComplete) {
        UserDetails header = redisUtils.getHeader(request);
        synchronized (this) {
            Adoption adoption = petService.queryAdoption(adoptionComplete.getPetId());
            if (adoption == null) {
                // 协议尚未创建
                ExceptionUtils.error(AGREEMENT_1_ERROR);
            } else if (!adoption.getAdId().equals(0)) {
                // 该宠物已被领养
                ExceptionUtils.error(AGREEMENT_2_ERROR);
            } else if (adoption.getUsId().equals(header.getId())) {
                // 该送养人不能填写领养人协议
                ExceptionUtils.error(AGREEMENT_3_ERROR);
            }
            adoptionComplete.setAd_id(header.getId());
            petService.adoptionComplete(adoptionComplete);
        }
        return Result.success();
    }

    @ApiOperation(value = "查询领养协议")
    @GetMapping(value = "/queryPetAgreement/{petId}", name = "领养协议完成-领养方")
    @CheckLoginStatus
    public Result queryAdoptionAgreement(@PathVariable Long petId) {

        return Result.success(petService.queryAdoptionAgreement(petId));

    }

    @ApiOperation(value = "查看寻宠海报信息")
    @PostMapping(value = "/querySearchPetPoster", name = "查看寻宠海报信息")
    public Result querySearchPetPoster(@RequestBody WxCodeUnLimit wxCodeUnLimit) {
        return Result.success(petService.querySearchPetPoster(wxCodeUnLimit));
    }

    @ApiOperation(value = "查看寻主海报信息")
    @PostMapping(value = "/querySearchPeoplePoster", name = "查看寻主海报信息")
    public Result querySearchPeoplePoster(@RequestBody WxCodeUnLimit wxCodeUnLimit) {
        return Result.success(petService.querySearchPeoplePoster(wxCodeUnLimit));
    }

    @ApiOperation(value = "查看领养海报信息")
    @PostMapping(value = "/queryPlacePoster", name = "查看领养海报信息")
    public Result queryPlacePoster(@RequestBody WxCodeUnLimit wxCodeUnLimit) {
        return Result.success(petService.queryPlacePoster(wxCodeUnLimit));
    }

    @ApiOperation(value = "拉取宠物品类列表")
    @GetMapping(value = "/getPetVarieties", name = " 拉取宠物品类列表")
    public Result getPetVarieties() {

        return Result.success(petService.getPetVarieties());
    }

    @ApiOperation(value ="查询宠物动态" )
    @GetMapping(value = "/getPetDynamic")
    @CheckLoginStatus
    public Result getPetDynamic(@RequestParam("id") Long id, @PageableDefault(page = 0,size = 10) Pageable pageable){
        return Result.success(petService.getPetDynamic(id,pageable));
    }


}
